<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="3">
            <el-form-item label="关联交班记录">
              <el-input v-model="queryParams.shiftHandoverRecordId" placeholder="请输入交班记录ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="接班人">
              <el-select v-model="queryParams.successionUserId" placeholder="请选择接班人" clearable filterable
                style="width: 100%">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="疑问反馈">
              <el-input v-model="queryParams.question" placeholder="请输入疑问反馈关键词" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-2">
      <el-button type="primary"  @click="handleCreate">
        <el-icon class="el-icon--left">
          <Plus />
        </el-icon>
        新建
      </el-button>
      <el-table :data="successionList" border v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column prop="id" label="记录ID" width="100" align="center" />
        <el-table-column prop="shiftHandoverRecordId" label="关联交班记录" width="120" align="center">
          <template #default="{ row }">
              {{ row.shiftHandoverRecordId }}
          </template>
        </el-table-column>
        <el-table-column prop="successionUserId" label="接班人" align="center">
          <template #default="{ row }">
            <el-tag size="medium">{{ getUserName(row.successionUserId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="successionTime" label="接班时间" align="center" width="180" />
        <el-table-column prop="question" label="疑问反馈" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.question" class="text-content">{{ row.question }}</span>
            <span v-else class="text-muted">无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small"  @click="handleView(row.id)">查看</el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 接班记录对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" :close-on-click-modal="false">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="关联交班记录" prop="shiftHandoverRecordId">
          <el-select v-model="form.shiftHandoverRecordId" placeholder="请选择交班记录" style="width: 100%"
            @change="handleShiftRecordChange">
            <el-option v-for="item in unSuccessionList" :key="item.id"
              :label="1" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="接班人" prop="successionUserId">
          <el-select v-model="form.successionUserId" placeholder="请选择接班人" style="width: 100%">
            <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="接班时间" prop="successionTime">
          <el-date-picker v-model="form.successionTime" type="datetime" placeholder="选择接班时间" style="width: 100%"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="疑问反馈">
          <el-input v-model="form.question" type="textarea" :rows="3" placeholder="请输入疑问反馈" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" title="接班记录详情" width="800px">
      <el-descriptions v-if="detailData" :column="2" border>
        <el-descriptions-item label="记录ID">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="关联交班记录">
            {{ detailData.shiftHandoverRecordId }}
        </el-descriptions-item>
        <el-descriptions-item label="接班人">{{ getUserName(detailData.successionUserId) }}</el-descriptions-item>
        <el-descriptions-item label="接班时间">{{ formatTime(detailData.successionTime) }}</el-descriptions-item>
        <el-descriptions-item label="疑问反馈" :span="2">
          <pre class="detail-pre">{{ detailData.question || '无' }}</pre>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API 导入
import {
  getSuccessionRecordList,
  createSuccessionRecord,
  updateSuccessionRecord,
  deleteSuccessionRecord,
  getUnSuccessionList,
  getSuccessionRecordDetail,
  getUserList
} from '@/api/prod_operate/prod_run/shift/takeover'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  shiftHandoverRecordId: undefined,
  successionUserId: undefined,
  successionTime: undefined,
  question: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  shiftHandoverRecordId: undefined,
  successionUserId: undefined,
  successionTime: '',
  question: ''
})

// 对话框控制
const dialog = reactive({
  visible: false,
  title: '新建接班记录',
  isEdit: false
})

const detailDialog = reactive({
  visible: false
})

// 表格数据
const successionList = ref([])
const userOptions = ref([])
const unSuccessionList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const detailData = ref(null)

// 表单验证规则
const rules = reactive({
  shiftHandoverRecordId: [
    { required: true, message: '请选择关联的交班记录', trigger: 'change' }
  ],
  successionUserId: [
    { required: true, message: '请选择接班人', trigger: 'change' }
  ],
  successionTime: [
    { required: true, message: '请选择接班时间', trigger: 'change' }
  ]
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return '未设置'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 根据用户ID获取用户名
const getUserName = (userId) => {
  const user = userOptions.value.find(item => item.id === userId)
  return user ? user.name : '未知用户'
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList()
    userOptions.value = res.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取未接班的交班记录列表
const fetchUnSuccessionList = async () => {
  try {
    const res = await getUnSuccessionList()
    unSuccessionList.value = res.data || []
  } catch (error) {
    console.error('获取未接班记录失败:', error)
    ElMessage.error('获取未接班记录失败')
  }
}

// 获取接班记录列表
const fetchSuccessionList = async () => {
  try {
    loading.value = true
    const res = await getSuccessionRecordList(queryParams)
    successionList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取接班记录列表失败:', error)
    ElMessage.error('获取接班记录列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchSuccessionList()
}

// 重置查询
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    shiftHandoverRecordId: undefined,
    successionUserId: undefined,
    question: undefined
  })
  fetchSuccessionList()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchSuccessionList()
}

const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchSuccessionList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新建接班记录
const handleCreate = async () => {
  await Promise.all([fetchUserList(), fetchUnSuccessionList()])
  Object.assign(form, {
    id: undefined,
    shiftHandoverRecordId: undefined,
    successionUserId: undefined,
    successionTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    question: ''
  })
  dialog.title = '新建接班记录'
  dialog.isEdit = false
  dialog.visible = true
}

// 编辑接班记录
const handleEdit = (row) => {
  Object.assign(form, row)
  dialog.title = '编辑接班记录'
  dialog.isEdit = true
  dialog.visible = true
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    if (dialog.isEdit) {
      await updateSuccessionRecord(form)
      ElMessage.success('更新成功')
    } else {
      await createSuccessionRecord(form)
      ElMessage.success('创建成功')
    }
    dialog.visible = false
    fetchSuccessionList()
  } catch (error) {
    console.error('操作失败:', error)
  }
}

// 查看详情
const handleView = async (id) => {
  try {
    const res = await getSuccessionRecordDetail(id)
    detailData.value = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取接班详情失败:', error)
    ElMessage.error('获取接班详情失败')
  }
}

// 查看交班详情
const handleViewShiftDetail = (shiftHandoverRecordId) => {
  // 这里可以跳转到交班记录详情页面
  // ElMessage.info(`查看交班记录 ${shiftHandoverRecordId} 的详情`)

}

// 关联交班记录变化处理
const handleShiftRecordChange = (value) => {
  if (value) {
    const selectedRecord = unSuccessionList.value.find(item => item.id === value)
    if (selectedRecord) {
      form.shiftHandoverRecordId = selectedRecord.id
    }
  }
}

// 初始化加载数据
onMounted(() => {
  fetchUserList()
  fetchSuccessionList()
})
</script>

<style scoped>

.search-card {
  margin-bottom: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  color: #303133;
}

.text-muted {
  color: #909399;
}

.text-content {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.detail-pre {
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
  font-family: inherit;
  line-height: 1.5;
}
</style>